import {
  DEVICE_TYPE_ENUM,
  DEVICE_TYPE_MATCH,
  DEVICE_TYPE_TRANS
} from "@/utils/constants";

/**
 * 正则表达式
 * 大于0的数字(不包括小数)
 */
export function RegInt(value: string) {
  return /^[1-9]\d*$/.test(value);
}

/**
 * 数组去重
 */
export function Unique(arr: any[]) {
  const hash = {};
  const result = [];
  for (var i = 0; i < arr.length; i++) {
    if (!(arr[i] in hash)) {
      hash[arr[i]] = true;
      result.push(arr[i]);
    }
  }
  return result;
}

export function convertToSeconds(days, hours, minutes) {
  // 每天有86400秒，每小时有3600秒，每分钟有60秒
  const secondsInDay = 86400;
  const secondsInHour = 3600;
  const secondsInMinute = 60;

  // 计算总秒数
  return (
    days * secondsInDay + hours * secondsInHour + minutes * secondsInMinute
  );
}

export function handleDeviceType(hiddenDeviceType: boolean, data: object) {
  if (hiddenDeviceType) {
    return data["device_type"];
  }
  // type sysType = "allDevice" | "makeTea" | "cabinet" | "factory";
  const arr = [
    "allDevice",
    "makeTea",
    "cabinet",
    "teaPowder",
    "factory",
    "pulper"
  ];
  // const systemType =
  //   (storageLocal().getItem<any>(`${responsiveStorageNameSpace()}system`)
  //     ?.type as sysType) || "makeTea";
  let systemType = "";
  const hrefArray = window.location.href.split("/");

  for (const str of arr) {
    const find = hrefArray.some(item => item === str);
    if (find) {
      systemType = str;
      break;
    }
  }
  if (systemType === "makeTea") {
    return DEVICE_TYPE_ENUM.MAKE_TEA;
  } else if (systemType === "cabinet") {
    return DEVICE_TYPE_ENUM.CABINET;
  } else if (systemType === "teaPowder") {
    return DEVICE_TYPE_ENUM.TEA_POWDER;
  } else if (systemType === "pulper") {
    return DEVICE_TYPE_ENUM.PULPER;
  }

  return data["device_type"];
}

export function handleImgURL(url: string) {
  const proxyPath = import.meta.env?.VITE_PROXY_PATH ?? "";
  const isInclude = url.includes("http");
  if (!isInclude) {
    return proxyPath.endsWith("/") ? proxyPath : proxyPath + "/";
  }
  return url.startsWith("http") ? "" : "/";
  // if (!isInclude) {
  //   return proxyPath + url.startsWith("/") ? url : "/" + url;
  // }
  // return url;
}

/**
 * 获取字符串中的字符数
 */
export function GetCharNum(text: string) {
  let sum = 0;
  for (let i = 0; i < text.length; i++) {
    if (text.charCodeAt(i) >= 0 && text.charCodeAt(i) <= 255) {
      sum = sum + 1;
    } else {
      sum = sum + 2; //中文标点或汉字算的两个字符
    }
  }
  return sum;
}

/**
 * 去除多余的0
 */
export function removeTrailingZeros(number: string) {
  if (number === "") {
    return 0;
  } else {
    if (number.toString().includes(".")) {
      return parseFloat(number);
    } else {
      return number;
    }
  }
}

/**
 * Converts weights of different units into a more readable format.
 * This function only processes when the input unit is grams (g), kilograms (kg), or tons (ton).
 * For kilograms and tons, it converts them into a string representation with non-zero decimal places removed.
 *
 * @param type The unit of weight, can only be "g", "kg", or "ton".
 * @param num The weight value, can be a number or a string representation of a number.
 * @returns Returns the processed weight value. If the unit is grams, it returns the original value.
 *          If the unit is kilograms or tons, it returns a string with non-zero decimal places removed.
 */
export function MeasuringWeight(
  type: "g" | "kg" | "ton",
  num: number | string
) {
  // When the unit is grams, no processing is needed, just return the original value.
  if (type == "g") {
    // This block is intentionally left blank.
  } else if (type == "kg") {
    // When the unit is kilograms, convert the weight value to a string with non-zero decimal places removed.
    num = removeTrailingZeros((Number(num) / 1000).toFixed(3));
  } else if (type == "ton") {
    // When the unit is tons, convert the weight value to a string with non-zero decimal places removed.
    num = removeTrailingZeros((Number(num) / 1000000).toFixed(6));
  }
  // Return the processed weight value.
  return num;
}

/**
 * 生成指定范围内的随机整数
 *
 * 该函数通过Math.random()方法生成一个[0, 1)范围内的随机数，然后通过数学运算
 * 将其转换为[min, max]范围内的随机整数这个函数存在的目的是为了提供一个简单
 * 方便的方式来获取一个指定范围内的随机整数，而不需要每次都写同样的逻辑
 *
 * @param min - 随机数范围的最小值（包含）
 * @param max - 随机数范围的最大值（包含）
 * @returns 返回[min, max]范围内的一个随机整数
 */
export function getRandomNumber(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * 判断是否是JSON对象
 */
export function IsJsonObject(obj: any) {
  if (obj != null && typeof obj == "object") {
    try {
      JSON.stringify(obj);
      return true;
    } catch (e) {
      return false;
    }
  }
  return false;
}

/**
 * JSON数组去重
 * @param array json Array
 * @param key string 唯一的key名，根据此键名进行去重
 */
export function UniqueArray(array: any[], key: string) {
  let result = [];
  if (IsJsonObject(array) && array.length > 0) {
    result = [array[0]];
  }
  for (let i = 1; i < array.length; i++) {
    const item = array[i];
    let repeat = false;
    for (let j = 0; j < result.length; j++) {
      if (item[key] == result[j][key]) {
        repeat = true;
        break;
      }
    }
    if (!repeat) {
      result.push(item);
    }
  }
  return result;
}

/**
 * 计量单位换算
 * type 类型 1 数量 2 重量 3 时间
 * num 计量
 */
export function MeasuringUnit(type: number, num: number) {
  let curNum = "";
  if (type == 1) {
    if (num < 10000) {
      curNum = String(num);
    } else if (num >= 10000 && num < 100000000) {
      curNum = removeTrailingZeros((num / 10000).toFixed(2)) + "万";
    } else if (num >= 100000000) {
      curNum = removeTrailingZeros((num / 100000000).toFixed(2)) + "亿";
    }
  } else if (type == 2) {
    if (num < 1000) {
      curNum = num + "g";
    } else if (num >= 1000 && num < 1000000) {
      curNum = removeTrailingZeros((num / 1000).toFixed(2)) + "kg";
    } else if (num >= 1000000) {
      curNum = removeTrailingZeros((num / 1000000).toFixed(2)) + "吨";
    }
  } else if (type == 3) {
    if (num < 1000) {
      curNum = "1秒";
    } else if (num >= 1000 && num < 1000 * 60) {
      curNum = (num / 1000).toFixed(0) + "秒";
    } else if (num >= 1000 * 60 && num < 1000 * 60 * 60) {
      curNum = (num / (1000 * 60)).toFixed(0) + "分钟";
    } else if (num >= 1000 * 60 * 60 && num < 1000 * 60 * 60 * 24) {
      curNum =
        removeTrailingZeros((num / (1000 * 60 * 60)).toFixed(1)) + "小时";
    } else if (num >= 1000 * 60 * 60 * 24) {
      curNum =
        removeTrailingZeros((num / (1000 * 60 * 60 * 24)).toFixed(2)) + "天";
    }
  }
  return curNum;
}

export const setDeviceTypeTrans = (device_model: string, { t, te }) => {
  if (!device_model) return "";
  const deviceModelSplit = device_model.split("ATT-");
  let device_type = "";
  try {
    for (const key in DEVICE_TYPE_MATCH) {
      const devKey = deviceModelSplit[1].substring(0, key.length);
      if (devKey === key) {
        device_type = DEVICE_TYPE_MATCH[key];
      }
    }
  } catch (error) {
    device_type = "";
  }
  return te(DEVICE_TYPE_TRANS[device_type])
    ? t(DEVICE_TYPE_TRANS[device_type])
    : device_type;
};
